<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
class Test extends Controller
{
    

    protected $payApi = [
        'jsapi' => 'https://api.mch.weixin.qq.com/hk/v3/transactions/jsapi'
    ];
    protected $queryApi = 'https://api.mch.weixin.qq.com/hk/v3/transactions/id/{id}';//查询订单接口
    protected $refundApi = 'https://api.mch.weixin.qq.com/hk/v3/refunds';//退单接口
    protected $refundNotify = '';//退单回调自定义
    protected $complaintsAPI = 'https://api.mch.weixin.qq.com/v3/merchant-service/complaints-v2';

    public function _initialize()
    {

    }
    
    /**
     * 下单
     */
    public function index(){
        print_r($this->complaints());
        /*
        $jsapiRes = json_decode($this->jsapiPay(1000),true);
        if($jsapiRes['prepay_id'])
        {
            $data['appid'] = $this->config()['appid'];
            $data['timeStamp'] = time();
            $data['nonceStr'] = $this->getRandomStr(32);
            $data['package'] = 'prepay_id='.$jsapiRes['prepay_id'];
            $data['signType'] = 'RSA';
            $data['paySign'] = $this->getPaySign($data);
            return json_encode($data);
        }*/
    }
    
    public function complaints(){
        $config = $this->config();
        $body = [
            'limit' => 50,
            'offset' => 0,
            'begin_date' => date('Y-m-d',(time()-86400*20) ),
            'end_date' => date('Y-m-d'),
            'complainted_mchid' => '1620905287',
        ];
        $body = [];
        $url = $this->complaintsAPI.'?limit=50&offset=0&begin_date='.date('Y-m-d',(time()-86400*20)).'&end_date='.date('Y-m-d').'&complainted_mchid=1620905287';
        $headers = $this->sign('GET',$url ,'');
        
        return $this->curl_post($url,'',$headers);
    }

    public function config(){
        return [
            'appid' => 'wx7e5c835298d1623c',
            'mchid' => '1620905287',
            'serial_no' => '6DC7F9F20ABE1EE85EEB3F34DD108FA2E0B69A89',//'67994B62E7E070AA8F1EAE8ED65724436370448E',//'6DC7F9F20ABE1EE85EEB3F34DD108FA2E0B69A89',
            'description' => '213123123',
            'notify' => 'http://nmn.mm7.cn/web/index.php%3Fr%3Dapi/test1/notify',//支付回调
        ];
    }
    
    /**
     * jsapi支付
     * @param $total  int  支付金额
     * @return mixed
     */
    public function jsapiPay($total){
        $config = $this->config();
        $body = [
            'appid' => $config['appid'],
            'mchid' => $config['mchid'],
            'description' => $config['description'],
            'out_trade_no' => $this->getOrderNo(),
            'notify_url' => $config['notify'],
            'amount' => [
                'total' => $total,
                'currency' => 'HKD'
            ],
            'trade_type'=> 'JSAPI',
            'merchant_category_code'=>'5111',
            "payer"=>["openid"=>"o9uzD4icxwDx0JvO7fMSNvlbBZ8Q"]//"o9uzD4pdScqcKLXDaHjyp9fhYB-Y"],
        ];
        $headers = $this->sign('POST',$this->getPayUrl('jsapi'),json_encode($body));
        return $this->curl_post($this->getPayUrl('jsapi'),json_encode($body),$headers);
    }


    /**
     * 支付通知
     */
    public function notify(){

    }

    /**
     * 签名
     * @param string $http_method    请求方式GET|POST
     * @param string $url            url
     * @param string $body           报文主体
     * @return array
     */
    public function sign($http_method = 'POST',$url = '',$body = ''){
        $mchPrivateKey = $this->getMchKey();//$this->certPubKey('/www/wwwroot/oa.com/wechatpay_67994B62E7E070AA8F1EAE8ED65724436370448E.pem');//
        $timestamp = time();
        $nonce = $this->getRandomStr(32);
        $urlParts = parse_url($url);
        //print_r($urlParts);
        $canonicalUrl = ($urlParts['path'] . (!empty($urlParts['query']) ? "?".$urlParts['query'] : ""));
        //echo $canonicalUrl;exit;
        $message = $http_method."\n".
            $canonicalUrl."\n".
            $timestamp."\n".
            $nonce."\n".
            $body."\n";
        openssl_sign($message, $rawSign, $mchPrivateKey, 'sha256WithRSAEncryption');
        $sign = base64_encode($rawSign);
        $config = $this->config();
        $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
            $config['mchid'], $nonce, $timestamp, $config['serial_no'], $sign);
        
        $headers = [
            'Accept: application/json',
            'User-Agent: */*',
            'Content-Type: application/json; charset=utf-8',
            'Authorization: '.$token,
        ];
        return $headers;
    }
    
    public function getPaySign($data){
        $mchPrivateKey = $this->getMchKey();
        $message = $data['appid']."\n".
            $data['timeStamp']."\n".
            $data['nonceStr']."\n".
            $data['package']."\n";
        openssl_sign($message, $rawSign, $mchPrivateKey, 'sha256WithRSAEncryption');
        $sign = base64_encode($rawSign);
        return $sign;
    }
    
    public function getMchKey(){
        $privateKey = file_get_contents('/www/wwwroot/oa.com/cert123561235165/'.$this->config()['mchid'].'/apiclient_key.pem');

        return openssl_get_privatekey($privateKey);
    }
    
    private function certPubKey($cert_path){
        $cert_path = file_get_contents($cert_path);
        $pub_key  = openssl_pkey_get_public($cert_path);
        if($pub_key){
            $keyData = openssl_pkey_get_details($pub_key);
            return $keyData['key'];
        }
        return false;
    }
    
    public function curl_post($url , $data, $headers)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
        //设置header头
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
        if($data)
        {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        //$request_header = curl_getinfo( $ch, CURLINFO_HEADER_OUT);
        //print_r($request_header);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    /**
     * 获得随机字符串
     * @param $len      integer       需要的长度
     * @param $special  bool      是否需要特殊符号
     * @return string       返回随机字符串
     */
    public function getRandomStr($len, $special=false){
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );

        if($special){
            $chars = array_merge($chars, array(
                "!", "@", "#", "$", "?", "|", "{", "/", ":", ";",
                "%", "^", "&", "*", "(", ")", "-", "_", "[", "]",
                "}", "<", ">", "~", "+", "=", ",", "."
            ));
        }

        $charsLen = count($chars) - 1;
        shuffle($chars);                            //打乱数组顺序
        $str = '';
        for($i=0; $i<$len; $i++){
            $str .= $chars[mt_rand(0, $charsLen)];    //随机取出一位
        }
        return $str;
    }
    
    public function getPayUrl($type = 'jsapi'){
        return $this->payApi[$type];
    }
    
    /**
     * 订单号
     */
    public function getOrderNo(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
}